package com.example.zqh.config.security;


import com.example.zqh.config.other.MyAccessDeniedHandler;
import com.example.zqh.config.other.MyauthenticationEntryPoint;
import com.example.zqh.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * SecurityConfig
 * zqh
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {




    @Autowired
    UserDetailsServiceImpl userDetailsServiceImpl;

    @Autowired
    MyauthenticationEntryPoint myauthenticationEntryPoint;

    @Autowired
    MyAccessDeniedHandler myAccessDeniedHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(passwordEncoder());
    }




    //放行接口
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/sysUser/login",
                "/file/uploading",
                "/swagger",
                "/css/**",
                "/js/**",
                "index.html",
                "favicon.ico",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/v2/api-docs/**",
                "/course/getCourses",
                "/teacher/getTeacherByPhotoUrl",
                "/comment/insertComment",
                //文件上传
                "/upload",
                //登录接口
                "/user/login",
                //注册用户接口
                "/user/register",
                //用户查询接口

                //获取所有用户的数量
                "/user/getAllUserNumber",
                //用户模糊查询
                "/user/fuzzyQuery",
                //通过性别查询用户的数量
                "/user/getNumberBySex",
                //通过性别查询用户，带分页
                "/user/getUsersBySexAndPageing",
                //分页查询某个商店的菜品
                "/food/getFoodsByPage",
                //分页查询所有菜品
                "/food/getAllFoodsByPaging",
                //查询某个商店菜品的数量
                "/food/getShopFoodNumberByShop_id",
                //获取所有商品数量
                "/shop/modifyTheStoreName",
                //通过id查询店铺
                "/shop/searchStoreByStoreId",
                //分页查询店铺
                "/shop/pagingQueryStore",
                //获取所有员工的数量
                "/emp/getAllEmpty",
                //员工分页查询
                "/emp/queryEmployeesByPage",
                //查询所有部门的数量
                "/dept/getTheCountOfAllDepartments",
                //分页查询部门
                "/dept/paginationToQueryAllDepartments",
                //查询评论
                "/comment/queryComments",
                //获取评论的数量
                "/comment/getCommentNumber",
                //获取所有商店的数量
                "/shop/getAllSp",
                //通过id获取食物信息
                "/food/queryTheInformationOfADishByTheDishId",
                //通过星级查询店铺，分页
                "/shop/searchStoresByStarRating",
                //通过星级查询不同商店的数量
                "/shop/getNumberByStart",
                //查询所有菜品的数量
                "/food/getTheQuantityOfAllDishes",
                //通过食物类型，分页查询食物
                "/food/getFoodsByTypeAndPage",
                //通过食物种类id，获取该种种类的数量
                "/food/getNumberByType",
                //食物的搜索引擎
                "/food/searchEngine",
                //通过名字查询多条食物
                "/food/searchByname",
                //超级会员登录接口
                "/user/AdminLogin"








        );
    }


    //跨越设置
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                cors()
                .and()
                .csrf().disable()
                .cors()
                .and()
                //关闭session
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers()
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .headers()
                .cacheControl();

//        //添加jwt 登录授权郭利奇
        http.addFilterBefore(jwtAuthencationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权未登录返回结果
        http.exceptionHandling()
                .accessDeniedHandler(myAccessDeniedHandler)
                .authenticationEntryPoint(myauthenticationEntryPoint);
    }

    @Bean
    public JwtAuthencationTokenFilter jwtAuthencationTokenFilter() {
        return new JwtAuthencationTokenFilter();
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
